﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using YuuzleComic.Common;

public partial class yzadmin_data_collect_u17 : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    private JObject result = new JObject();
    static CookieContainer cookies = new CookieContainer();
    string domain = "http://www.mkzhan.com";
    string baseUrl = "http://www.u17.com/comic_list/th{0}_gr{1}_ca{2}_ss{3}_ob{4}_ac{5}_as{6}_wm{7}_p{8}.html";
    string searchUrl = "http://so.u17.com/all/{0}/m{1}_p{2}.html";
    string th = "99";
    string gr = "99";
    string ca = "99";
    string ss = "0";
    string ob = "0";
    string ac = "0";
    string as1 = "0";
    string wm = "0";
    int p = 1;
    string xgd = "0";
    private string getUrl()
    {
        return string.Format(baseUrl, new object[] { th, gr, ca, ss, ob, ac, as1, wm, p });
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "import":
                    this.ProcessImport();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessImport()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            string[] urlArray = Request["zjurl"].Split('\n');
            foreach (string url in urlArray)
            {
                List<string> tpurl = new List<string>();
                HtmlDocument doc = new HtmlDocument();
                foreach (string item in url.Split('|'))
	            {
                    doc = webClient.Load(item);
                    HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//*[@id=\"selectpage1\"]/p/a");
                    foreach (HtmlNode node in nodes)
                    {
                        if (node.Attributes["href"].Value != item)
                        {
                            doc = webClient.Load(node.Attributes["href"].Value);
                        }
                        string s = doc.DocumentNode.SelectSingleNode("//*[@class='comic_read_img']/script").InnerText.Trim();
                        s = s.Replace("document.write(eee('", "").Replace("'));", "");
                        tpurl.Add(Input.GetImagesSrc(Input.DecodeFrom64(s)));
                    }
	            }
                
                YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
                zj.cid = Convert.ToInt32(Request["id"]);
                zj.zjmc = doc.DocumentNode.SelectSingleNode("//*[@id=\"readtop\"]/h1/a[last()]").InnerText;
                zj.time = DateTime.Now;
                zj.isdownload = false;
                zj.tpadd = Request["tpadd"] + zj.zjmc.Split(' ')[0] + "/";
                zj.tps = tpurl.Count;
                zj.tpurl = string.Join("|", tpurl.ToArray());
                YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
                if (urlArray.Length == 1 && !string.IsNullOrEmpty(Request["zjid"]))
                {
                    zj.id = int.Parse(Request["zjid"]);
                    zjbll.Update(zj);
                }
                else
                {
                    zjbll.Add(zj);
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    

    private void ProcessSingle()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            HtmlDocument doc = webClient.Load(Request["url"]);
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@id=\"workinfo\"]");
            result.Add("mhmc", node.SelectSingleNode("h1/text()").InnerText.Trim());
            result.Add("mhfm", node.SelectSingleNode("div[1]/a/img").Attributes["src"].Value);
            result.Add("zzmc", node.SelectSingleNode("h1/span/a").InnerText);
            result.Add("classname", node.SelectSingleNode("div//div[@class=\"comic\"]/p/span[2]").InnerText);
            result.Add("zt", node.SelectSingleNode("div//div[@class=\"comic\"]/p/span[3]").InnerText);
            result.Add("tc", node.SelectSingleNode("div//div[@class=\"comic\"]/p/span[1]").InnerText);
            result.Add("time", doc.DocumentNode.SelectSingleNode("//*[@id=\"chapterlist\"]/p/text()[last()]").InnerText.Split('：')[1]);
            result.Add("mhjj", node.SelectSingleNode("div//div[@class=\"comic\"]/div[@class='intro']/text()").InnerText.Trim());
            result.Add("mhjs", node.SelectSingleNode("div//div[@class=\"comic\"]/div[@class='intro']/text()").InnerHtml.Trim());
            JArray chapters = new JArray();
            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//*[@id=\"chapterlist\"]/ul/li/a");
            if (nodes != null)
            {
                foreach (HtmlNode item in nodes)
                {
                    JObject chapter = new JObject();
                    chapter.Add("zjmc", item.Attributes["title"].Value);
                    chapter.Add("zjurl", item.Attributes["href"].Value);
                    chapter.Add("tps", item.NextSibling.InnerText);
                    chapters.Add(chapter);
                }
            }
            result.Add("chapters", chapters);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }
    }

    private void ProcessList()
    {
        try
        {
            if (!string.IsNullOrEmpty(Request["th"]))
            {
                th = Request["th"];
            }
            if (!string.IsNullOrEmpty(Request["gr"]))
            {
                gr = Request["gr"];
            }
            if (!string.IsNullOrEmpty(Request["ca"]))
            {
                ca = Request["ca"];
            }
            if (!string.IsNullOrEmpty(Request["ss"]))
            {
                ss = Request["ss"];
            }
            if (!string.IsNullOrEmpty(Request["ob"]))
            {
                ob = Request["ob"];
            }
            if (!string.IsNullOrEmpty(Request["ac"]))
            {
                ac = Request["ac"];
            }
            if (!string.IsNullOrEmpty(Request["as"]))
            {
                as1 = Request["as"];
            }
            if (!string.IsNullOrEmpty(Request["wm"]))
            {
                wm = Request["wm"];
            }
            p = Convert.ToInt32(Request["page"]);
            HtmlWeb webClient = this.getWebClient();
            JArray data = new JArray();
            HtmlDocument doc;
            HtmlNodeCollection nodes;
            if (string.IsNullOrEmpty(Request["query"]))
            {
                doc = webClient.Load(this.getUrl());
                nodes = doc.DocumentNode.SelectNodes("//div[@class=\"comiclist\"]/ul/li");
            }else
            {
                doc = webClient.Load(string.Format(searchUrl, new object[] { Request["query"].Trim(), xgd, p }));
                nodes = doc.DocumentNode.SelectNodes("//div[@class=\"comiclist\"]/ul/li/div[1]");
	        }
            foreach (HtmlNode node in nodes)
            {
                JObject jo = new JObject();
                jo.Add("mhmc", node.SelectSingleNode("div[2]/h3/strong/a").InnerText);
                jo.Add("mhurl", node.SelectSingleNode("div[2]/h3/strong/a").Attributes["href"].Value);
                jo.Add("zzmc", node.SelectSingleNode("div[2]/h3/a[last()]").InnerText);
                jo.Add("time", node.SelectSingleNode("div[2]/h3/span[1]").InnerText);
                data.Add(jo);
            }
            result.Add("data", data);
            int total = data.Count;
            if (doc.DocumentNode.SelectSingleNode("//div[starts-with(@class,'page')]/em") != null)
            {
                total = int.Parse(doc.DocumentNode.SelectSingleNode("//div[starts-with(@class,'page')]/em").InnerText.Split('/')[1]) * int.Parse(Request["limit"]);
            }
            result.Add("total", total);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }

    }

    private HtmlWeb getWebClient()
    {
        HtmlWeb webClient = new HtmlWeb();
        if (cookies.Count == 0)
        {
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://cas.sdo.com/authen/staticLogin.jsonp?callback=staticLogin_JSONPMethod&inputUserId=seo1214&password=htcherog3&appId=200020500&areaId=1&serviceUrl=http%3A%2F%2Fpassport.u17.com%2Fsdo%2Fsnda_login_signature.php&productVersion=v5&frameType=3&locale=zh_CN&version=21&tag=20&authenSource=2&productId=2&autoLoginFlag=1");
            myHttpWebRequest.Accept = "*/*";
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
            myHttpWebRequest.CookieContainer = new CookieContainer();
            myHttpWebRequest.GetResponse().Close();
            cookies = myHttpWebRequest.CookieContainer;
        }
        HtmlAgilityPack.HtmlWeb.PreRequestHandler handler = delegate(HttpWebRequest request)
        {
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.CookieContainer = cookies;
            request.Timeout = 500000;
            return true;
        };
        webClient.PreRequest += handler;
        return webClient;
    }
}